import {
  Injectable,
  NotFoundException,
  BadRequestException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Team } from './entities/team.entity';
import { CreateTeamDto } from './dto/create-team.dto';
import { UpdateTeamDto } from './dto/update-team.dto';
import { UserService } from '../user/user.service';

@Injectable()
export class TeamService {
  constructor(
    @InjectRepository(Team)
    private readonly teamRepository: Repository<Team>,
    private readonly userService: UserService,
  ) {}

  async create(createTeamDto: CreateTeamDto, creatorId: number): Promise<Team> {
    const team = this.teamRepository.create({
      ...createTeamDto,
      creatorId,
    });

    const savedTeam = await this.teamRepository.save(team);

    // 自动将创建者添加为团队成员
    await this.addMember(savedTeam.id, creatorId);

    // 重新查询以获取完整信息
    return this.findOne(savedTeam.id);
  }

  async findAll(): Promise<Team[]> {
    return await this.teamRepository.find({
      relations: ['creator', 'members'],
      order: { createdAt: 'DESC' },
    });
  }

  async findUserTeams(userId: number): Promise<Team[]> {
    return await this.teamRepository
      .createQueryBuilder('team')
      .leftJoinAndSelect('team.creator', 'creator')
      .leftJoinAndSelect('team.members', 'members')
      .where('members.id = :userId', { userId })
      .orderBy('team.createdAt', 'DESC')
      .getMany();
  }

  async findOne(id: number): Promise<Team> {
    const team = await this.teamRepository.findOne({
      where: { id },
      relations: ['creator', 'members'],
    });

    if (!team) {
      throw new NotFoundException(`Team with ID ${id} not found`);
    }

    return team;
  }

  async update(id: number, updateTeamDto: UpdateTeamDto): Promise<Team> {
    const team = await this.findOne(id);
    Object.assign(team, updateTeamDto);
    await this.teamRepository.save(team);
    return this.findOne(id);
  }

  async remove(id: number): Promise<void> {
    const team = await this.findOne(id);
    await this.teamRepository.remove(team);
  }

  async addMember(teamId: number, userId: number): Promise<Team> {
    const team = await this.findOne(teamId);
    const user = await this.userService.findById(userId);

    if (!user) {
      throw new NotFoundException(`User with ID ${userId} not found`);
    }

    // 检查用户是否已经是成员
    const isMember = team.members.some((member) => member.id === userId);
    if (isMember) {
      throw new BadRequestException('User is already a member of this team');
    }

    team.members.push(user);
    await this.teamRepository.save(team);

    return this.findOne(teamId);
  }

  async removeMember(teamId: number, userId: number): Promise<Team> {
    const team = await this.findOne(teamId);

    // 不能移除创建者
    if (team.creatorId === userId) {
      throw new BadRequestException('Cannot remove team creator');
    }

    team.members = team.members.filter((member) => member.id !== userId);
    await this.teamRepository.save(team);

    return this.findOne(teamId);
  }
}
